package club.banyuan;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class DownloadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(5000);
        Socket accept = serverSocket.accept();
        InputStream inputStream = accept.getInputStream();
        OutputStream outputStream = accept.getOutputStream();

        // 向客户端传入文件数量
        outputStream.write(ByteToInt.toBytes(4));

        // 服务器端提供下载的文件数组
        File[] files = new File[4];
        files[0] = new File("/Users/edz/banyuan/Java/19.IO/practice/02.CaesarCipher/src/Decode.java");
        files[1] = new File("/Users/edz/banyuan/Java/19.IO/practice/02.CaesarCipher/src/Encode.java");
        files[2] = new File("/Users/edz/banyuan/Java/19.IO/practice/02.CaesarCipher/alice.code");
        files[3] = new File("/Users/edz/banyuan/Java/19.IO/practice/02.CaesarCipher/alice.code.decode");

        FileInfo[] fileInfos = new FileInfo[4];
        String[] fileInfoStrs = new String[4];
        for (int i = 0; i < 4; i++) {
            fileInfos[i] = new FileInfo(files[i].getName(), fileInfos.length);
            fileInfoStrs[i] = JSONObject.toJSONString(fileInfos[i]);
            outputStream.write(ByteToInt.toBytes(fileInfoStrs[i].getBytes().length));
            outputStream.write(fileInfoStrs[i].getBytes());
        }

        // 获取客户端选择下载的文件编号
        int choose = ByteToInt.toInt(getBytes(inputStream, 4));

        // 将客户端选择下载的文件传给客户端
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(files[choose-1]));
        byte[] buf = new byte[1024];
        int count = bufferedInputStream.read(buf);
        while (count > 0) {
            outputStream.write(buf, 0, count);
            count = bufferedInputStream.read(buf);
        }
        bufferedInputStream.close();
        accept.close();
    }


    private static byte[] getBytes(InputStream inputStream, int total) throws IOException {
        byte[] lengthBytes = new byte[total];
        int len = inputStream.read(lengthBytes);
        if (len != lengthBytes.length) {
            throw new IllegalArgumentException("读取长度错误");
        }
        return lengthBytes;
    }
}
